<template>
    <div class="home card">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="12" v-for="item in FormItemGroups" :key="item.valueKey">
                    <el-form-item v-if="item.type === 'input'" :label="item.label" :prop="item.valueKey">
                        <el-input v-model="ruleForm[item.valueKey as Api_ClueManager.OrderFormKey]" maxlength="50"
                            v-bind="item.props" />
                    </el-form-item>
                    <el-form-item v-else-if="item.type === 'textarea'" :label="item.label" :prop="item.valueKey">
                        <el-input v-model="ruleForm[item.valueKey as Api_ClueManager.OrderFormKey]" type="textarea"
                            maxlength="255" show-word-limit :autosize="{ minRows: 3, maxRows: 6 }"
                            v-bind="item.props" />
                    </el-form-item>
                    <el-form-item v-else-if="item.type === 'radio'" :label="item.label" :prop="item.valueKey">
                        <el-radio-group v-model="ruleForm[item.valueKey as Api_ClueManager.OrderFormKey]"
                            :disabled="isEdit">
                            <el-radio v-for="optionsItem in item.options" :label="optionsItem.value">{{
                                optionsItem.label
                                }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-else-if="item.type === 'select'" :label="item.label" :prop="item.valueKey">
                        <el-select v-model="ruleForm[item.valueKey as Api_ClueManager.OrderFormKey]"
                            v-bind="item.props">
                            <el-option v-for="optionsItem in item.options" :label="optionsItem.label"
                                :value="optionsItem.value" clearable />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-else-if="item.type === 'cascader'" :label="item.label" :prop="item.valueKey">
                        <el-cascader v-model="ruleForm[item.valueKey as Api_ClueManager.OrderFormKey]"
                            v-bind="item.props" :options="item.options" :props="CustomCascaderProps" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="12">
                    <div class="custom-table-box">
                        <div class="clue-title-text">线下机构</div>
                        <new-table ref="proTable1" v-bind="state1" />
                    </div>
                </el-col>
                <el-col :xs="24" :sm="24" :md="12">
                    <div class="custom-table-box">
                        <div class="clue-title-text">线上机构</div>
                        <new-table ref="proTable2" v-bind="state2" />
                    </div>
                </el-col>
            </el-row>
            <div class="flx-center width-full mt35">
                <el-button @click="resetForm(ruleFormRef)" class="mr15"
                    v-if="props.handleType === HandleType.ADD">重置</el-button>
                <el-button @click="emits('handleCancel')" class="mr15" v-else>取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    提交
                </el-button>
            </div>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, watchEffect } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElNotification, ElTable } from "element-plus";
import { RelationList, JigouLineType, CustomCascaderProps, FormatCourseidsAndCityids } from '../const';
import utils from 'src/utils'
import NewTable from 'src/components/NewTable/index.vue'
import { postClueAdd, postClueUpdate } from '../api';
import { HandleType } from '../const';
import { useSourceList, useCourseList, useCityList, useJigouList, useUserData } from "src/hooks";
import { regExp_phone } from 'src/common/const/reg-exp';

const [SourseList] = useSourceList();
const [CourseList] = useCourseList();
const [CityList] = useCityList();

const emits = defineEmits(['handleUpdated', 'handleCancel'])
const props = defineProps({
    orderData: {
        type: Object,
        default: {}
    },
    handleType: {
        type: String,
        default: 'ADD'
    }
})

const isEdit = ref<boolean>(false);


// ProTable 实例
const proTable1 = ref<InstanceType<typeof ElTable>>();
const proTable2 = ref<InstanceType<typeof ElTable>>();
const ruleFormRef = ref<FormInstance>()
const originFormValue: Api_ClueManager.OrderForm = {
    studentname: '',
    contacttype: '',
    mobile: '',
    sourceid: '',
    courseid: '',
    cityid: '',
    wechat: '',
    qq: '',
    tips: '',
    online: '',
}

const ruleForm = reactive<Api_ClueManager.OrderForm>({
    studentname: '',
    contacttype: '1',
    mobile: '',
    sourceid: '',
    courseid: '',
    cityid: '',
    wechat: '',
    qq: '',
    tips: '',
    online: '',
})

// 表格配置项
const columns1 = reactive<TableHeader[]>([
    { prop: "jigouName", label: "机构名" },
    // { prop: "area", label: "区" }
]);

const columns2 = reactive<TableHeader[]>([
    { prop: "jigouName", label: "机构名" }
]);



const state1 = reactive({
    tableHeader: <TableHeader[]>[
        ...columns1
    ],
    tableData: <any[]>[],
    isIndex: false,
    rowKey: 'jigouid',
    isSelection: true,
    paginationFlag: false,
    selectionIds: ''
})
const state2 = reactive({
    tableHeader: <TableHeader[]>[
        ...columns2
    ],
    tableData: <any[]>[],
    isIndex: false,
    rowKey: 'jigouid',
    isSelection: true,
    paginationFlag: false,
    selectionIds: ''
})

const rules = reactive<FormRules<Api_ClueManager.OrderForm>>({
    studentname: [
        { required: true, message: '请填写学员名称', trigger: 'blur' }
    ],
    mobile: [
        { required: true, message: '请选填写学员手机号码', trigger: 'blur' },
        { pattern: regExp_phone, message: '请填写正确的手机号码', trigger: 'blur' }
    ],
    phone: [
        { pattern: regExp_phone, message: '请填写正确的手机号码', trigger: 'blur' }
    ],
    sourceid: [
        { required: true, message: '请选择学员线索来源', trigger: 'blur' }
    ],
    courseid: [
        { required: true, message: '请选择学员意向课程', trigger: 'blur' }
    ],
    cityid: [
        { required: true, message: '请选择学员城市', trigger: 'blur' }
    ]
})


watch([props], () => {
    // 如果是edit状态则需要重新赋值给原有的变量
    if (props.handleType === HandleType.EIDT) {
        isEdit.value = true
        const currentData: Api_ClueManager.ClueItemType = props.orderData.value
        Object.keys(currentData).forEach(key => {
            if (!key.startsWith('courseid')) {
                const value: any = currentData[key as keyof Api_ClueManager.ClueItemType]
                // 赋值的时候需要把驼峰的key变成全小写
                if (key === 'jiGouVOList') {
                    const selectionIds = ((value as any[]) || []).map(item => item.jigouid)
                    if (`${currentData.online}` === JigouLineType.OFF_LINE) {
                        state1.selectionIds = selectionIds.join(',')
                    } else {
                        state2.selectionIds = selectionIds.join(',')
                    }
                } else if (key === 'city') {
                    try {
                        if (value !== undefined && value !== null) {
                            ruleForm.cityid = [value.id, value.children[0].id]
                        }
                    } catch (error) {
                        console.log(error);
                    }

                } else {
                    const cKey = key.toLocaleLowerCase();
                    if (key === 'sourceid') {
                        ruleForm[cKey as Api_ClueManager.OrderFormKey] = Number(value)
                    } else {
                        ruleForm[cKey as Api_ClueManager.OrderFormKey] = typeof value === 'number' ? `${value}` : value
                    }
                }
            }
        })
        ruleForm.courseid = [Number(currentData.courseid), Number(currentData.courseid2), Number(currentData.courseid3)]
    }
}, {
    immediate: true
})
const FormItemGroups = ref<Api_ClueManager.FormItemType[]>([])
watchEffect(() => {
    if (ruleForm.courseid && ruleForm.cityid) {
        if (Array.isArray(ruleForm.courseid) && ruleForm.courseid.length >= 3 && Array.isArray(ruleForm.cityid) && ruleForm.cityid.length >= 2) {
            const courseid3 = ruleForm.courseid[2]
            const cityid = ruleForm.cityid[1]
            const [JigouList1] = useJigouList({ courseid3, cityid, online: JigouLineType.OFF_LINE })
            const [JigouList2] = useJigouList({ courseid3, cityid, online: JigouLineType.ON_LINE })
            state1.tableData = JigouList1
            state2.tableData = JigouList2
        }

    }
})
watchEffect(() => {
    FormItemGroups.value = [
        {
            label: '主要联系方式',
            valueKey: 'contacttype',
            type: 'radio',
            options: [...RelationList],
            props: {
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: '手机',
            valueKey: 'mobile',
            type: 'input',
            props: {
                placeholder: isEdit.value ? '' : '请填写学员手机号码',
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: '学员名称',
            valueKey: 'studentname',
            type: 'input',
            props: {
                placeholder: isEdit.value ? '' : '请填写学员名称',
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: '来源',
            valueKey: 'sourceid',
            type: 'select',
            options: SourseList,
            props: {
                placeholder: isEdit.value ? '' : '请选择学员线索来源',
                disabled: isEdit.value,
                clearable: true,
                filterable: true
            }
        },
        {
            label: '意向课程',
            valueKey: 'courseid',
            type: 'cascader',
            options: [...CourseList],
            props: {
                placeholder: isEdit.value ? '' : '请选择学员意向课程',
                disabled: isEdit.value,
                clearable: true,
                filterable: true
            }
        },
        {
            label: '意向城市',
            valueKey: 'cityid',
            type: 'cascader',
            options: [...CityList],
            props: {
                placeholder: isEdit.value ? '' : '请选择学员意向城市',
                disabled: isEdit.value,
                clearable: true,
                filterable: true
            }
        },
        {
            label: '微信',
            valueKey: 'wechat',
            type: 'input',
            props: {
                placeholder: isEdit.value ? '' : '请填写学员微信号',
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: '电话',
            valueKey: 'phone',
            type: 'input',
            props: {
                placeholder: isEdit.value ? '' : '学员存在多个号码时填写',
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: 'QQ',
            valueKey: 'qq',
            type: 'input',
            props: {
                placeholder: isEdit.value ? '' : '请填写学员的联系QQ',
                disabled: isEdit.value,
                clearable: true
            }
        },
        {
            label: '备注',
            valueKey: 'tips',
            type: 'textarea',
            props: {
                placeholder: '请填写备注',
                clearable: true
            }
        }
    ]
})
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields();
    Object.keys(originFormValue).forEach(key => {
        ruleForm[key as Api_ClueManager.OrderFormKey] = originFormValue[key as Api_ClueManager.OrderFormKey]
    })
    proTable1.value?.clearSelection();
    proTable2.value?.clearSelection();
}

const _handleSubmit = async (formData: any) => {
    let requestFunc = null, msg_success = '', callback_success = null
    if (!isEdit.value) {
        requestFunc = postClueAdd
        msg_success = '添加成功'
        callback_success = () => resetForm(ruleFormRef.value as FormInstance)
    } else {
        requestFunc = postClueUpdate
        msg_success = '更新成功'
        callback_success = () => emits('handleUpdated')
        // 如果是脱敏的字段 更新的时候不用传给后端
        const desensitizationWords = ['mobile', 'studentname', 'wechat', 'phone', 'qq']
        desensitizationWords.forEach(key => (formData[key] && delete formData[key]))
    }
    const { code } = await requestFunc(formData)
    utils.commonNotification({
        condition: `${code}` === '0',
        msg_success,
        callback_success
    })
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (ruleForm.contacttype === '1' && !ruleForm.mobile) {
                ElNotification({
                    message: "请填写学员手机号码",
                    type: "warning"
                })
                return
            }
            if (ruleForm.contacttype === '2' && !ruleForm.wechat) {
                ElNotification({
                    message: "请填写学员微信号",
                    type: "warning"
                })
                return
            }
            const proTableSelected_1 = (proTable1.value as any)?.selectedListIds
            const proTableSelected_2 = (proTable2.value as any)?.selectedListIds
            console.log(proTableSelected_1, proTableSelected_2);

            if (!proTableSelected_1?.length && !proTableSelected_2?.length) {
                ElNotification({
                    message: "请选择机构",
                    type: "warning"
                })
                return
            }
            const copyRuleForm = utils.cloneDeep(ruleForm)
            if (proTableSelected_1?.length) {
                copyRuleForm.jigouids = proTableSelected_1.join(',')
                copyRuleForm.online = JigouLineType.OFF_LINE
            } else {
                copyRuleForm.jigouids = proTableSelected_2.join(',')
                copyRuleForm.online = JigouLineType.ON_LINE
            }
            FormatCourseidsAndCityids(copyRuleForm)
            const [useData] = useUserData();
            copyRuleForm.departmentid = useData.departMentid
            console.log('submit!', copyRuleForm)
            _handleSubmit({ ...copyRuleForm })
        } else {
            // console.log('error submit!', fields)
        }
    })
}

</script>

<style scoped lang="scss">
.custom-table-box {
    .clue-title-text {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 5px;
    }

    .container {
        padding: 0 !important;
    }
}
</style>